import nmap
import tkinter as tk


# 扫描进行时
def perform_scan(ip_address, port_range, arguments):
    try:
        # 创建扫描器对象
        nm = nmap.PortScanner()
        # 开始扫描
        nm.scan(ip_address, port_range, arguments=arguments)
        result = f'Host: {ip_address}\n'
        for host in nm.all_hosts():
            # 主机的IP地址和主机名
            result += f'Host: {host} ({nm[host].hostname()})\n'
            # 主机的状态（如up或down）
            result += f'State: {nm[host].state()}\n'
            for proto in nm[host].all_protocols():
                result += f'Protocol: {proto}\n'
                l_port = nm[host][proto].keys()
                for port in sorted(l_port):
                    # 存储每个端口的状态（如open或closed）
                    result += f'port: {port}\tstate: {nm[host][proto][port]["state"]}\n'
        return result
    except Exception as e:
        return f'Scan error for {ip_address}: {str(e)}'


# 更新进程状态
def update_progress(progress, futures, result_text, root):
    completed_futures = [f for f in futures if f.done()]
    progress['value'] = len(completed_futures)
    for future in completed_futures:
        result = future.result()
        result_text.insert(tk.END, result + '\n')
        # 从列表中移除完成的进程任务
        futures.remove(future)

    # 如果进程表非空就继续进行
    if futures:
        root.after(100, update_progress, progress, futures, result_text, root)
    # 进程表空就停止
    else:
        progress.stop()
